import { createStore } from 'vuex'

const setLocalCartList = (state) => {
  const { cartList } = state
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}
const getLocalCartList = () => {
  return JSON.parse(localStorage.cartList || '{}')
}
export default createStore({
  state: {
    cartList: getLocalCartList()
  },
  mutations: {
    changeCartItem (state, payload) {
      const {
        shopId,
        shopName,
        productId,
        productInfo,
        number
      } = payload
      console.log(payload)
      let shopInfo = state.cartList[shopId]
      if (!shopInfo) {
        shopInfo = {
          name: shopName,
          productList: {}
        }
      }
      let product = shopInfo.productList[productId]
      if (!product) {
        product = productInfo
        product.count = 0
        product.checked = false
      }
      product.count += number
      if (product.count > 0) {
        product.checked = true
      }
      if (product.count < 0) {
        product.count = 0
      }
      console.log(product)
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    changeCartItemState (state, payload) {
      const {
        shopId,
        productId,
        checked
      } = payload
      const shopInfo = state.cartList[shopId]
      const product = shopInfo.productList[productId]
      product.checked = checked
      shopInfo.productList[productId] = product
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    changeCartState (state, payload) {
      const {
        shopId
      } = payload
      const productList = state.cartList[shopId].productList
      for (const key in productList) {
        const product = productList[key]
        product.checked = !product.checked
      }
      setLocalCartList(state)
    },
    clearCart (state, payload) {
      const {
        shopId
      } = payload
      state.cartList[shopId].productList = {}
      setLocalCartList(state)
    }
  },
  actions: {},
  modules: {}
})
